<template>
  <el-dialog :title="!dataForm.id ?'新增':'修改'" :close-on-click-modal="false" :visible.sync="visible">
    <el-form  :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="110px">
      <!-- <el-form-item label="" prop="userId">
        <el-select v-model="dataForm.userId" filterable :multiple="false"  placeholder="请输" clearable :disabled="dataForm.id">
          <el-option v-for="item in studentList" :key="item.userId" :label="item.realName" :value="item.userId"></el-option>
        </el-select>
      </el-form-item> -->
      <el-form-item label="车间名称" prop="workshopName">
        <el-input v-model="dataForm.workshopName" placeholder="请输入车间名称" maxlength="20" show-word-limit clearable ></el-input>
      </el-form-item>
      <el-form-item label="设备编号" prop="deviceId">
        <el-input v-model="dataForm.deviceId" placeholder="请输入设备编号(英文或数字)" maxlength="30" show-word-limit clearable :disabled="dataForm.id"></el-input>
      </el-form-item>
      <el-form-item label="设备类型" prop="deviceType" >
        <el-radio-group v-model="dataForm.deviceType"  >
            <el-radio  v-for="type in deviceTypes" :label="type.value" :key="type.value"  border>{{ type.name }}</el-radio>
        </el-radio-group>
        </el-form-item>
        <el-row>
        <el-col :span="12"> 
        <el-form-item label="设备名称" prop="deviceName">
        <el-input v-model="dataForm.deviceName" placeholder="请输入设备名称" maxlength="20" show-word-limit clearable  style="width: 80%;" ></el-input>
        </el-form-item>
       </el-col>
       <el-col :span="12"> 
      <el-form-item label="设备型号" prop="deviceModel">
        <el-input v-model="dataForm.deviceModel" placeholder="请输入设备型号" maxlength="20" show-word-limit clearable  style="width: 80%;" ></el-input>
      </el-form-item>
    </el-col>
      </el-row>
      <el-row>
      <el-col :span="12">   <el-form-item v-show="!dataForm.id" label="生产日期" prop="produceTime" >
       <el-date-picker v-model="dataForm.produceTime" placeholder="请输入生产日期"  type="date" style="width: 80%;"      :picker-options="pickerOptions"> </el-date-picker>  
      </el-form-item>
    
      </el-col>
      <el-col :span="12">  <el-form-item v-show="!dataForm.id" label="开始使用日期" prop="startUseTime">
          <el-date-picker v-model="dataForm.startUseTime" placeholder="请输入开始使用日期"  type="datetime" style="width: 80%;"   :picker-options="pickerOptions"></el-date-picker>
      </el-form-item>
       
    </el-col>
      </el-row>
      <el-row>
      <el-col :span="12"> 
     <el-form-item label="制造厂" prop="factory">
        <el-input v-model="dataForm.factory" placeholder="请输入制造厂"   clearable  style="width: 80%;" ></el-input>
       </el-form-item>
    </el-col>
    <el-col :span="12"> 
      <el-form-item label="维保到期" prop="maintenanceTime">
        <el-date-picker v-model="dataForm.maintenanceTime" placeholder="请输入维保到期"  type="date" style="width: 80%;"></el-date-picker>
      </el-form-item>
    </el-col>
      </el-row>
      <!-- 单选 -->
<el-form-item label="保养计划: " prop="maintenancePlan">
    <el-radio-group v-model="dataForm.maintenancePlan" @change="changeMaintenancePlan">
        <el-radio  label = "1" border >方案一</el-radio>
        <el-radio  label = "2" border >方案二</el-radio>
    </el-radio-group>
</el-form-item>

<template v-if="dataForm.maintenancePlan === '1'" >
<el-row :gutter="25">
    <el-col :span="11">
        <el-form-item label="保养周期（天）" prop="maintenanceCycle">
            <el-input v-model.number="dataForm.maintenanceCycle" placeholder="保养周期" clearable></el-input>
        </el-form-item>
        <el-form-item label="保养计划详情: ">
            <el-button type="text" @click="open1">点击打开查询方案一详情</el-button>
        </el-form-item>
    </el-col>
  <el-col :span="11">
    <el-form-item label="提前提醒（天）" prop="advanceTime" >
            <el-input v-model.number="dataForm.advanceTime" placeholder="提前预警时间" clearable></el-input>
        </el-form-item>
        
    </el-col>
</el-row>
</template>

<template v-if="dataForm.maintenancePlan === '2'">
      <el-form-item label="使用时长（小时）" prop="maintenanceCycle">
        <el-input v-model.number="dataForm.maintenanceCycle" placeholder="请输入使用时长" clearable></el-input>
      </el-form-item>
      <el-form-item label="保养计划详情: ">
        <el-button type="text" @click="open2">点击打开查询方案二详情</el-button>
    </el-form-item>
</template>


      <el-form-item label="传感器ID" prop="sensorId">
        <el-input v-model="dataForm.sensorId" placeholder="请输入传感器ID(英文或数字)" maxlength="20" show-word-limit clearable  ></el-input>
      </el-form-item> 
      <el-form-item label="备注" prop="notes">
        <el-input v-model="dataForm.notes" placeholder="请输入备注" maxlength="100"  type="textarea" :autosize="{ minRows: 2, maxRows: 2}" show-word-limit style="width: 100%;" ></el-input>
      </el-form-item>
    <el-form-item label="设备视频" >
      <el-upload
  class="video-uploader"
     name="file"
  :action="this.$http.adornUrl('/dss/deviceInformation/upload/video')"
  :headers="tokenInfo"
  :show-file-list="false"
  :on-success="handleVideoSuccess"
  :before-upload="beforeVideoUpload"
  accept="video/*">
  <video v-if="videoUrl" :src="videoUrl" controls class="video"></video>
  <div v-else class="upload-area">
    <i class="el-icon-plus upload-icon"></i>
    <div class="el-upload__tip">支持MP4/AVI格式，大小不超过100MB</div>
  </div>
</el-upload>
    </el-form-item>

    </el-form>

    <span slot="footer" class="dialog-footer">
      <el-button @click="visible=false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit( )">确定</el-button>
    </span>
  </el-dialog>
</template>

<style>
.video-uploader .video {
  width: 360px;
  height: 200px;
  object-fit: contain;
}
.upload-area {
  border: 1px dashed #d9d9d9;
  padding: 20px;
  text-align: center;
}
</style>

<script>
import dayjs from 'dayjs';

  export default{
    
    data(){
      // 自定义校验规则：确保 maintenanceCycle > advanceTime
      const validateXAndY = (rule, value, callback) => {
            const { maintenancePlan, maintenanceCycle, advanceTime } = this.dataForm;
            if (maintenancePlan === '1') {
                // 方案一：maintenanceCycle > advanceTime
                if (maintenanceCycle <= advanceTime) {
                    callback(new Error('保养周期必须大于提前日期'));
                } else {
                    callback();
                }
            } else if (maintenancePlan === '2') {
                // 方案二：maintenanceCycle = advanceTime
                if (maintenanceCycle <= 0) {
                    callback(new Error('使用时长必须大于0'));
                } else {
                    callback();
                }
            } else {
                callback();
            }
        };
      return{
        pickerOptions: {
          disabledDate(time) {
            return time.getTime() > Date.now();
          }},
          videoUrl:'',
          tokenInfo: {
          'token': this.$cookie.get('token')
        },
        dictList:[],
        deviceTypes:[],
        visible:false,
        dataForm:{
          video:'',
          id:0,
          workshopName:'',
          deviceId:'',
          deviceType:'',
          deviceName:'',
          deviceModel:'',
          factory:'',
          produceTime:'',
          startUseTime:'',
          maintenanceTime:'',
          notes:'',
          sensorId:'',
          maintenancePlan:'',
          maintenanceCycle:'',
          advanceTime:''
        },
        ages:[],

        dataRule:{
          deviceId:[
            {required:true, message: '请输入设备编号',trigger:'blur'},
            { 
            pattern: /^[A-Za-z0-9]*$/, 
            message: '只能输入英文和数字', 
            trigger: 'blur' 
          },
          {validator: this.deviceIdRule, trigger: 'blur' }
          ],deviceType:[
            {required:true, message: '请选择设备类型',trigger:'blur'},
          ],deviceName:[
            {required:true, message: '请输入设备名称',trigger:'blur'},
          ],deviceModel:[
            {required:true, message: '请输入设备型号',trigger:'blur'},
            { 
            pattern: /^[A-Za-z0-9]*$/, 
            message: '只能输入英文和数字', 
            trigger: 'blur' 
          }
          ],factory:[
            {required:true, message: '请输入制造厂',trigger:'blur'},
          ],produceTime:[
            {required:true, message: '请选择生产日期',trigger:'blur'},
            { validator: this.produceTimeRule, trigger: 'blur'}
          ],startUseTime:[
            {required:true, message: '请选择开始使用日期',trigger:'blur'},
            { validator: this.startUseTimeRule, trigger: 'blur'}
          ],
          maintenanceTime:[
            {required:true, message: '请请选择维保到期时间',trigger:'blur'},
          { validator: this.maintenanceTimeRule, trigger: 'blur'}
          ], sensorId:[
            {required:true, message: '请输入传感器ID',trigger:'blur'},
            { 
            pattern: /^[A-Za-z0-9]*$/, 
            message: '只能输入英文和数字', 
            trigger: 'blur' 
          }
          ],
                maintenancePlan:[
                    { required: true, message: '请选择保养方式', trigger: 'blur'},
                ],
                maintenanceCycle:[
                    { required: true, message: '请输入值', trigger: 'blur' },
                    { type:'number', message: '必须为数字', trigger: ['blur', 'change']},
                    { validator: validateXAndY, trigger: 'blur' },
                ],
                advanceTime:[
                    { required: true, message: '请输入值', trigger: 'blur' },
                    { type:'number', message: '必须为数字', trigger: ['blur', 'change']},
                    { validator: validateXAndY, trigger: 'blur' },
                ]
        

        }
      }
    },


    methods:{
      beforeVideoUpload(file) {
    const isVideo = /^video\/(mp4|avi)$/.test(file.type);
    const isLt100M = file.size / 1024 / 1024 < 100;
    
    if (!isVideo) {
      this.$message.error('仅支持MP4/AVI格式视频!');
    }
    if (!isLt100M) {
      this.$message.error('视频大小不能超过100MB!');
    }
    return isVideo && isLt100M;
  },
  handleVideoSuccess(res, file) {
    this.videoUrl = URL.createObjectURL(file.raw);
    this.dataForm.video = res.msg
    console.log( this.dataForm.video );
    
  },
      deviceIdRule(rule, value, callback) {
       
        if (!this.dataForm.id && this.dataList.some(DssDeviceInformationDTO => DssDeviceInformationDTO.deviceId === this.dataForm.deviceId ) ){
        callback(new Error('设备已存在'));
      }else {
        callback();
      }
        },
      produceTimeRule(rule, value, callback) {
     
        if (value && new Date(value) > new Date(this.dataForm.maintenanceTime) ) {
        callback(new Error('生产日期必须小于维保到期日期'));
      }else if (value && new Date(value) > new Date(this.dataForm.startUseTime) ) {
        callback(new Error('生产日期必须小于开始使用日期'));
      }else if (value && new Date(value) > new Date(this.dataForm.startUseTime) && new Date(value) > new Date(this.dataForm.maintenanceTime)) {
        callback(new Error('生产日期必须小于开始使用日期和维保到期日期'));
      } else {
        callback();
      }
      },
      startUseTimeRule(rule, value, callback) {
      if (value && new Date(value) < new Date(this.dataForm.produceTime)) {
        callback(new Error('开始使用日期必须大于生产日期'));
      } else {
        callback();
      }
    },
    maintenanceTimeRule(rule, value, callback) {
      if (value && new Date(value) <= new Date(this.dataForm.produceTime)) {
        callback(new Error('维保到期日期必须大于生产日期'));
      }else if (value && new Date(this.dataForm.maintenanceTime) <= new Date(this.dataForm.startUseTime) ) {
        callback(new Error('维保到期日期必须大于开始使用日期'));
      } else {
        callback();
      }
    },   
    changeMaintenancePlan(plan) {
            this.dataForm.maintenancePlan = plan;
            // 重置相关字段
            this.dataForm.maintenanceCycle = '';
            this.dataForm.advanceTime = '';
        },
        open1(){
            const message =`每<strong> ${this.dataForm.maintenanceCycle}天</strong>保养一次，到期前<strong> ${this.dataForm.advanceTime}天</strong>提醒`
            this.$alert(message, '方案一', {
                confirmButtonText:'知道了',
                dangerouslyUseHTMLString: true
            })
        },
        open2(){
            this.$alert(`亮灯总时长到达<strong> ${this.dataForm.maintenanceCycle}小时</strong>提醒保养`, '方案二', {
                confirmButtonText:'知道了',
                dangerouslyUseHTMLString: true
            })
        },
      init(id,dataList){
        this.dataList=dataList
        this.dataForm.id=id||0
        this.$http({
          url:this.$http.adornUrl('/dss/deviceInformation/dict/list'),
          method:'get',
          params:this.$http.adornParams()
        }).then(({data})=>{
          
          this.deviceTypes=data.dictMap.deviceTypeList
       //   console.log(this.deviceTypes)
        }).then(() => {
          
        this.visible=true
        this.$nextTick(()=>{
          this.$refs['dataForm'].resetFields()
          this.videoUrl=''
          if (this.dataForm.id){
            this.$http({
              url:this.$http.adornUrl(`/dss/deviceInformation/info/${this.dataForm.id}`),
              method:'get',
              params:this.$http.adornParams()
            }).then(({data})=>{
              if (data&&data.code===0) {
                this.dataForm.workshopName=data.deviceInformation.workshopName
                this.dataForm.deviceId=data.deviceInformation.deviceId
                this.dataForm.deviceType=data.deviceInformation.deviceType
                this.dataForm.deviceName=data.deviceInformation.deviceName
                this.dataForm.deviceModel=data.deviceInformation.deviceModel
                this.dataForm.factory=data.deviceInformation.factory
                this.dataForm.produceTime=data.deviceInformation.produceTime
                this.dataForm.startUseTime=data.deviceInformation.startUseTime
                this.dataForm.maintenanceTime=data.deviceInformation.maintenanceTime
                this.dataForm.notes=data.deviceInformation.notes
                this.dataForm.sensorId=data.deviceInformation.sensorId
                this.dataForm.maintenancePlan = data.deviceInformation.maintenancePlan
                            this.dataForm.maintenanceCycle = data.deviceInformation.maintenanceCycle
                            this.dataForm.advanceTime = data.deviceInformation.advanceTime
                            this.dataForm.video = data.deviceInformation.video
                            if(this.dataForm.video){
                  this.videoUrl = this.dataForm.video
                }
              }
            })
          }
        })
      })
      },
      dataFormSubmit(){  
                   this.$refs['dataForm'].validate((valid)=>{
          // if (!this.dataForm.id && this.dataList.some(DssDeviceInformationDTO => DssDeviceInformationDTO.deviceId === this.dataForm.deviceId ) ) {
          //   this.$message({
          //         message:'该设备信息已存在，请上传其他设备信息！',
          //         type:'error',
          //         duration:1500,
          //         onClose:() =>{
          //           this.$emit('refreshDataList')
          //         }
          //       })
          //                     }else 
         if (valid){
              console.log("wadadwadw");
                
            this.$http({
              url:this.$http.adornUrl(`/dss/deviceInformation/${!this.dataForm.id?'save':'update'}`),
              method:'post',
              data:this.$http.adornData({
                'id':this.dataForm.id||undefined,
                'workshopName':this.dataForm.workshopName,
                'deviceId':this.dataForm.deviceId,
                'deviceType':this.dataForm.deviceType,
                'deviceName':this.dataForm.deviceName,
                'deviceModel':this.dataForm.deviceModel,
                'factory':this.dataForm.factory,
                'produceTime':dayjs(this.dataForm.produceTime).format('YYYY-MM-DD HH:mm:ss'),
                'startUseTime':dayjs(this.dataForm.startUseTime).format('YYYY-MM-DD HH:mm:ss'),
                'maintenanceTime':dayjs(this.dataForm.maintenanceTime).format('YYYY-MM-DD HH:mm:ss'),
                'notes':this.dataForm.notes,
                'sensorId':this.dataForm.sensorId,
                'maintenancePlan':this.dataForm.maintenancePlan,
                'maintenanceCycle':this.dataForm.maintenanceCycle,
                            'advanceTime': this.dataForm.advanceTime,
                            'video':this.dataForm.video
                            
              })
            }).then(({data})=>{
              if (data&&data.code===0) {
                this.$message({
                  message:'操作成功',
                  type:'success',
                  duration:1500,
                  onClose:() =>{
                    this.visible=false
                    this.$emit('refreshDataList')
                  }
                })
              } else {
                this.$message.error(data.msg)
              }
            })
          }
        } )
      }
    }
  }
</script>
